$(function () {
    function Admin() {
        this.ajaxUrl = '//practice-api.bjjixin.cn';
        this.devUrl = '//10.52.14.21';
        this.isloader = true;
        this.isloaderVideo = true;
        this.uploader = '';
        this.uploaderVideo = '';
        this.answerPage = 0;
        this.answerArr = []
        this.isChecked = true;
        this.baseUrl = {
            // 登录
            login: this.ajaxUrl + '/backend/v1/user/login',
            // 退出
            exitlogin: this.ajaxUrl + '/backend/v1/user/logout',
            // 获取用户信息
            loginuser: this.ajaxUrl + '/backend/v1/user',
            // 订单列表
            orderlist: this.ajaxUrl + '/backend/v1/order',
            // 名师风采
            teacherlist: this.ajaxUrl + '/backend/v1/teacher',
            // 老师修改
            teacherListMod: this.ajaxUrl + '/backend/v1/teacher/view',
            // 老师增加
            teacherListAdd: this.ajaxUrl + '/backend/v1/teacher/create',
            // 老师删除
            teacherListRemove: this.ajaxUrl + '/backend/v1/teacher/del',
            // 老师更新
            teacherListUpdate: this.ajaxUrl + '/backend/v1/teacher/update',
            // 友情链接列表
            linksList: this.ajaxUrl + '/backend/v1/links',
            // 友情链接删除
            linksListRemove: this.ajaxUrl + '/backend/v1/links/del',
            // 友情链接添加
            linksListAdd: this.ajaxUrl + '/backend/v1/links/create',
            // 新闻列表
            newsList: this.ajaxUrl + '/backend/v1/tidings',
            // 新闻删除
            newsListRemove: this.ajaxUrl + '/backend/v1/tidings/del',
            // 新闻添加
            newsListAdd: this.ajaxUrl + '/backend/v1/tidings/create',
            // banner
            bannerList: this.ajaxUrl + '/backend/v1/banner',
            // banner删除
            bannerListRemove: this.ajaxUrl + '/backend/v1/banner/del',
            // banner添加
            bannerListAdd: this.ajaxUrl + '/backend/v1/banner/create',
            // banner更新
            bannerListUpdate: this.ajaxUrl + '/backend/v1/banner/update',
            // banner详情
            bannerListMod: this.ajaxUrl + '/backend/v1/banner/view',

            // 顶级分类导航列表作废
            //categoryList : this.ajaxUrl +'/backend/v1/category',
            // 顶级分类导航添加作废
            //categoryListAdd : this.ajaxUrl +'/backend/v1/category/create',
            // 顶级分类导航详情作废
            //categoryListMod : this.ajaxUrl +'/backend/v1/category/view',
            // 顶级分类导航更新作废
            //categoryListUpdate : this.ajaxUrl +'/backend/v1/category/update',
            // 顶级分类导航删除作废
            //categoryListRemove : this.ajaxUrl +'/backend/v1/category/delete',

            // 顶级分类导航列表
            classifyList: this.ajaxUrl + '/backend/v1/classify',
            // 顶级分类导航添加
            classifyListAdd: this.ajaxUrl + '/backend/v1/classify/create',
            // 顶级分类导航详情
            classifyListMod: this.ajaxUrl + '/backend/v1/classify/view',
            // 顶级分类导航更新
            classifyListUpdate: this.ajaxUrl + '/backend/v1/classify/update',
            // 顶级分类导航删除
            classifyListRemove: this.ajaxUrl + '/backend/v1/classify/delete',

            // 顶级分类导航列表
            classifyLineList: this.ajaxUrl + '/backend/v1/classify_line',
            // 顶级分类导航添加
            classifyLineListAdd: this.ajaxUrl + '/backend/v1/classify_line/create',
            // 顶级分类导航详情
            classifyLineListMod: this.ajaxUrl + '/backend/v1/classify_line/view',
            // 顶级分类导航更新
            classifyLineListUpdate: this.ajaxUrl + '/backend/v1/classify_line/update',
            // 顶级分类导航删除
            classifyLineListRemove: this.ajaxUrl + '/backend/v1/classify_line/delete',

            // 商品
            commonList: this.ajaxUrl + '/backend/v1/goods',
            // 商品添加
            commonListAdd: this.ajaxUrl + '/backend/v1/goods/create',
            // 商品上下架
            commonListType: this.ajaxUrl + '/backend/v1/goods/operation',
            // 商品详情
            commonListMod: this.ajaxUrl + '/backend/v1/goods/detail',
            // 商品更新
            commonListUpdate: this.ajaxUrl + '/backend/v1/goods/update',

            // 题库
            bankList: this.ajaxUrl + '/backend/v1/topic',
            // 题库添加
            bankListtAdd: this.ajaxUrl + '/backend/v1/topic/create',
            // 题库详情
            bankListMod: this.ajaxUrl + '/backend/v1/topic/detail',
            // 题库更新
            bankListUpdate: this.ajaxUrl + '/backend/v1/topic/update',
            // 题库删除
            bankListRemove: this.ajaxUrl + '/backend/v1/topic/delete',

            // 视频
            videoList: this.ajaxUrl + '/backend/v1/video',
            // 视频添加
            videoListtAdd: this.ajaxUrl + '/backend/v1/video/create',
            // 视频详情
            videoListMod: this.ajaxUrl + '/backend/v1/video/detail',
            // 视频更新
            videoListUpdate: this.ajaxUrl + '/backend/v1/video/update',
            // 视频删除
            videoListRemove: this.ajaxUrl + '/backend/v1/video/delete',

            // 商品分类
            commongoodstypeList: this.ajaxUrl + '/common/v1/index/goods_type',
            // 商品类别
            commongoodsassortList: this.ajaxUrl + '/common/v1/index/goods_assort',
            // 分类导航
            commonclassifytList: this.ajaxUrl + '/common/v1/classify',
            // 题目类型
            commonindexList: this.ajaxUrl + '/common/v1/index',

            // 用户异常列表日志
            userList: this.ajaxUrl + '/backend/v1/abnormal',

            // 学生帐号列表
            studentUserList: this.ajaxUrl + '/backend/v1/student',
            // 学生帐号禁用
            studentUserListDisable: this.ajaxUrl + '/backend/v1/student/disable',
            // 学生帐号添加
            studentUserListAdd: this.ajaxUrl + '/backend/v1/student/create',
            // 学生帐号密码更新
            studentUserListUpdate: this.ajaxUrl + '/backend/v1/student/update',
            // 学生帐号列表--开通课程(所有课程列表)
            studentUserListOpenAll: this.ajaxUrl + '/backend/v1/goods/shelvesGoods',
            // 学生帐号列表--开通课程
            studentUserListOpen: this.ajaxUrl + '/backend/v1/order/giveOut',


            // 运营帐号列表
            operateUserList: this.ajaxUrl + '/backend/v1/user',
            // 运营帐号禁用
            operateUserListDisable: this.ajaxUrl + '/backend/v1/user/disable',
            // 运营帐号添加
            operateUserListAdd: this.ajaxUrl + '/backend/v1/user/create',
            // 运营帐号密码更新
            operateUserListUpdate: this.ajaxUrl + '/backend/v1/user/up_password',
            // 单独上传图片接口
            uploadImg: this.ajaxUrl + '/backend/v1/topic/uploadImg'



        };
    };
    Admin.prototype.init = function () {
        this.eventFn();
        this.wHeight();
        if (this.getCookierl('istooken')) {
            $('.login_txt').text('退出')
            $('.user_txt').text(this.getCookierl('usertxt'))
        }


    };
    Admin.prototype.ajaxFn = function (ajaxList, callback) {
        var _this = this;
        //ajaxList.data.access_token = this.getCookierl('cookval');
        var cookval = _this.getCookierl('cookval');
        var token_type = _this.getCookierl('token_type');
        $.ajax({
            url: ajaxList.url,
            type: ajaxList.type,
            dataType: 'json',
            data: ajaxList.data,
            // beforeSend: function (XMLHttpRequest) {
            //     XMLHttpRequest.setRequestHeader("Authorization",_this.getCookierl('token_type') +' '+ _this.getCookierl('cookval'));
            // },
            headers: {
                Authorization: _this.getCookierl('token_type') + ' ' + _this.getCookierl('cookval')
            }
        }).done(function (res) {
            callback && callback(res)
        }).error(function (XHR, textStatus, errorThrown) {
            if (XHR.status == 403) {
                if (XHR.responseJSON.code == 40003) {
                    //TODO 提示框
                    layer.msg('用户未登录');
                    window.location.replace("/login.html");
                }
            } else if (XHR.status == 400) {
                if (XHR.responseJSON.code == 40000) {
                    layer.msg(XHR.responseJSON.message)
                }
            }

            //TODO
        });
    };
    Admin.prototype.wHeight = function () {
        var windowHeight = $(window).height();
        $('#page-wrapper').height(windowHeight);
    };

    Admin.prototype.getCookierl = function (name) {
        var cookieName = encodeURIComponent(name) + "="
            , cookieStart = document.cookie.indexOf(cookieName)
            , cookieValue = null;
        if (cookieStart > -1) {
            var cookieEnd = document.cookie.indexOf(";", cookieStart);
            if (cookieEnd == -1) {
                cookieEnd = document.cookie.length;
            }
            cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
        }
        return cookieValue;
    };
    Admin.prototype.setCookierl = function (name, value, expires, path, domain, secure) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expires);
        var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
        cookieText += ";expires=" + exdate.toGMTString();
        if (path) {
            cookieText += ";path=" + path;
        }
        if (domain) {
            cookieText += ";domain=" + domain;
        }
        if (secure) {
            cookieText += ";secure";
        }
        document.cookie = cookieText;
    };
    // Admin.prototype.clearCookierl = function (k, domain) {
    //     this.setCookierl(name, "", -1);
    // };
    Admin.prototype.clearCookierl = function (name) {
        var keys = document.cookie.match(/[^ =;]+(?==)/g);
        if (!keys || !keys.length) return;
        for (var i = keys.length; i--;) {
            document.cookie = keys[i] + '=0;expires=Thu, 01 Jan 1970 00:00:00 GMT;';
        }
    };
    Admin.prototype.eventFn = function () {
        //关闭弹窗
        var _this = this
        $('body').on('click', '.fa-times', function () {
            $('#graybg_pop , .teacher_pop').remove();
            _this.answerPage = 0;
            _this.answerArr = []
            _this.isChecked = true;
        })


        if ($('.login_txt').length > 0) {
            $('body').on('click', '.login_txt', function () {
                layer.open({
                    type: 1
                    , title: false //不显示标题栏
                    , closeBtn: false
                    , area: '300px;'
                    , shade: 0.8
                    , id: 'LAY_layuipro' //设定一个id，防止重复弹出
                    , btn: ['确定', '取消']
                    , btnAlign: 'c'
                    , moveType: 1 //拖拽模式，0或者1
                    , content: '<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">确定要退出吗？</div>'
                    , yes: function () {
                        $('.layui-layer-shade, .layui-layer').hide();
                        admin.ajaxFn(
                            {
                                url: admin.baseUrl.exitlogin,
                                type: 'POST',
                                data: {}
                            },
                            function (data) {
                                window.open('/login.html', '_self');
                                _this.clearCookierl()
                                // this.clearCookierl('token_type')
                                // this.clearCookierl('cookval')
                                // this.clearCookierl('istooken')
                            }
                        )
                    }

                });
            })
        }
    };
    Admin.prototype.webuploaderFn = function (labelTxt, adminUrl, imagesTit, imagesTxt, imagesType) {
        var _this = this
        this.uploader != '' ? this.uploader.reset() : this.uploader
        this.uploader = WebUploader.create({
            // auto: false,
            config: {
                thumbWidth: 110, //缩略图宽度，可省略，默认为110
                thumbHeight: 110, //缩略图高度，可省略，默认为110
                wrapId: 'filePicker', //必填
            },
            resize: false, // 不压缩image
            method: "post",
            // sendAsBinary : true,//文件上传二进制流
            // fileNumLimit: 10,//验证文件总数量, 超出则不允许加入队列
            fileSingleSizeLimit: 4 * 1024 * 1024 * 1024,//验证单个文件大小是否超出限制, 超出则不允许加入队列
            server: adminUrl,// 文件接收服务端
            // formData:{},
            pick: {
                id: '#filePicker',
                innerHTML: labelTxt
            },
            fileVal: 'img',
            chunked: true,//是否要分片处理大文件上传
            threads: true, //上传并发数
            chunkSize: 3 * 1024 * 1024, //分片上传，每片2M，默认是5M
            prepareNextFile: true,//上传当前分片时预处理下一分片
            chunkRetry: 1, //如果某个分片由于网络问题出错，允许自动重传次数
            duplicate: false, //重复选择
            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
            disableGlobalDnd: true,
            accept: {
                title: imagesTit,
                extensions: imagesTxt,
                mimeTypes: imagesType
            }
        });
        this.uploader.on('fileQueued', function (file) {
            _this.isloader = false;
             _this.uploader.makeThumb( file, function( error, dataSrc ) {
                if ( !error ) {
                    $('.viewThumb').html('<img src="'+dataSrc+'">');
                }
            });
        });
        this.uploader.on('uploadError', function (file,response,http) {
            console.log(http.getStatus(),http.getResponseAsJson());
            if(http.getStatus() == 400){
                if(http.getResponseAsJson().code == 40000){
                    layer.msg(http.getResponseAsJson().message)
                }
            }
        });
        //生成预览缩略图;

    };

    Admin.prototype.webuploaderVideoFn = function (labelTxt, adminUrl, imagesTit, imagesTxt, imagesType) {
        var _this = this;
        this.uploaderVideo != '' ? this.uploaderVideo.reset() : this.uploaderVideo;
        this.uploaderVideo = WebUploader.create({
            // auto: false,
            resize: false, // 不压缩image
            method: "post",
            // sendAsBinary : true,//文件上传二进制流
            // fileNumLimit: 10,//验证文件总数量, 超出则不允许加入队列
            fileSingleSizeLimit: 4 * 1024 * 1024 * 1024,//验证单个文件大小是否超出限制, 超出则不允许加入队列
            server: adminUrl,// 文件接收服务端
            // formData:{},
            pick: {
                id: '#filePickerVideo',
                innerHTML: labelTxt
            },
            fileVal: 'video',
            chunked: true,//是否要分片处理大文件上传
            threads: true, //上传并发数
            chunkSize: 3 * 1024 * 1024, //分片上传，每片2M，默认是5M
            prepareNextFile: true,//上传当前分片时预处理下一分片
            chunkRetry: 1, //如果某个分片由于网络问题出错，允许自动重传次数
            duplicate: false, //重复选择
            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
            disableGlobalDnd: true,
            accept: {
                title: imagesTit,
                extensions: imagesTxt,
                mimeTypes: imagesType
            }
        });
        this.uploaderVideo.on('fileQueued', function (file) {
            uploaderfile = file.source.name;
            _this.isloaderVideo = false;
        });
        this.uploader.on('uploadError', function (file) {
            console.log(http.getStatus(),http.getResponseAsJson());
            if(http.getStatus() == 400){
                if(http.getResponseAsJson().code == 40000){
                    layer.msg(http.getResponseAsJson().message)
                }
            }
        });
    };

    Admin.prototype.uploaderImg = function (opt) {
        var _this = this
        _this.defalutOpt={
            severUrl : admin.baseUrl.uploadImg,
            title :'Images',
            fileVal : 'img',
            extensions :'gif,jpg,jpeg,png',
            mimeTypes :'image/gif,image/jpg,image/jpeg,image/png',
            token : admin.getCookierl('cookval'),
        }
        var options = $.extend({}, this.defalutOpt, opt, true)

        options.uploader = WebUploader.create({
            auto: true,
            config: {
                thumbWidth: 110, //缩略图宽度，可省略，默认为110
                thumbHeight: 110, //缩略图高度，可省略，默认为110
                wrapId: 'filePicker', //必填
            },
            resize: false, // 不压缩image
            method: "post",
            // sendAsBinary : true,//文件上传二进制流
            // fileNumLimit: 10,//验证文件总数量, 超出则不允许加入队列
            fileSingleSizeLimit: 4 * 1024 * 1024 * 1024,//验证单个文件大小是否超出限制, 超出则不允许加入队列
            server: options.severUrl,// 文件接收服务端
            formData:{
                token : options.token
            },
            pick: {
                id: options.id,
                innerHTML: options.innerHTML
            },
            fileVal: options.fileVal,
            chunked: true,//是否要分片处理大文件上传
            threads: true, //上传并发数
            chunkSize: 3 * 1024 * 1024, //分片上传，每片2M，默认是5M
            prepareNextFile: true,//上传当前分片时预处理下一分片
            chunkRetry: 1, //如果某个分片由于网络问题出错，允许自动重传次数
            duplicate: false, //重复选择
            // 禁掉全局的拖拽功能。这样不会出现图片拖进页面的时候，把图片打开。
            disableGlobalDnd: true,
            accept: {
                title: options.title,
                extensions: options.extensions,
                mimeTypes: options.mimeTypes
            }
        });
        options.uploader.on('uploadSuccess', options.uploadSuccess);
        options.uploader.on('fileQueued', function (file) {
            _this.isloader = false;
             options.uploader.makeThumb( file, function( error, dataSrc ) {
                if ( !error ) {
                    $('.viewThumb').html('<img src="'+dataSrc+'">');
                }
            });
        });
        options.uploader.on('uploadError', function (file,response,http) {
            console.log(http.getStatus(),http.getResponseAsJson());
            if(http.getStatus() == 400){
                if(http.getResponseAsJson().code == 40000){
                    layer.msg(http.getResponseAsJson().message)
                }
            }
        });
        //生成预览缩略图;
        if (options.uploader.state === 'ready') {
            options.uploader.upload();
        } else if (options.uploader.state === 'paused') {
            options.uploader.upload();
        } else if (options.uploader.state === 'uploading') {
            options.uploader.stop();
        }

    };

    admin = new Admin();
    admin.init();
});